define([
    'zepto',
    'underscore',
    'backbone',
    "text!templates/tied/bindCard.html",
    "text!templates/agreement.html",
    "wTools",
    "area",
    "validate"

], function ($, _, Backbone, template,agreement) {
    return Backbone.View.extend({
        $el: $main,
        el: $main0,
        $isEmpty: true,
        template: _.template(template),
        templateAgreement: _.template(agreement),
        events: {
            "tap #btn": "btn",
            "blur #username":"nameTest",
            "blur #bankCode":"bankTest",
            "tap #showAgreement": "showAgreement",
            "tap #closeAgreement": "closeAgreement",
            "input #username":"limitLen",
            "input #bankCode":"limitLen",
        },
        initialize: function () {
            $("#head_back").hide();
            var postData = {
                "token": wData.urlData.token
            }, that = this;
            wAjaxForm("getTokenInfo", "", postData, function (result) {
                if (result.success) {
                    wData.returnUrl = result.tokenInfo.returnUrl;
                    wData.userNo = result.tokenInfo.userNo;
                    wData.trxId = result.tokenInfo.trxId;
                    wData.status = 'F';
                    that.render(wData);
                }else{
                    wTips("请重试");
                }
            });
        },
        back: function () {
            history.back();
        },
        render: function (data) {
            var html = this.template(data);
            this.$el.html(html);
            this.isEmpty();
        },
        btn: function () {
            var bOK = $('#btn').hasClass('disabled' ) || this.isEmpty() || !this.bankTest() || !this.nameTest();
            if(bOK){
                return;
            };
            var postData = {
                "token": wData.urlData.token,
                'cardNo': $('#bankCode').val()
            };
            wAjaxForm('queryCardBin', '', postData, function(result){
                result = JSON.parse(result);

                wData.username = $('#username').val();
                wData.bankCode = $('#bankCode').val();
                

                if(result!==''){
                    wData.cardName = result.cardName;
                    if(result.cardType == 'CC'){
                        location.hash = 'creaditCard';
                    }
                    else if(result.cardType =='DC'){
                        location.hash = 'debitCard';
                    }
                    else {
                        wTips('当前不支持卡类型！')
                    }
                }
                else{
                    wTips('系统异常！')
                }

            });

        },
        nameTest: function(event) {
            var data = $('#username').val();
            var result = wCheck(data,'username');
            $('#username').parents('li').find('.tip').html(result.error)
            return result.success
        },
        bankTest: function() {
            var data = $('#bankCode').val();
            var result = this.luhmCheck(data);
            $('#bankCode').parents('li').find('.tip').html(result.error)
            return result.success
        },
        isEmpty: function(event) {
            var _el = $('.listInfo').find('input');
            for(var i = 0; i<_el.size();i++){
                if(_el.eq(i).val()==''){
                    this.$isEmpty = true;
                    break;
                }else{
                    this.$isEmpty = false;
                }
            }
            if(!this.$isEmpty){
                $('#btn').removeClass('disabled');
            }
            else{
                $('#btn').addClass('disabled');
            }
            return this.$isEmpty;
        },
        //显示协议内容
        showAgreement: function () {
            this.$el.append(this.templateAgreement());
            App.title("快捷支付服务协议");
        },
        //阅读并接受协议
        closeAgreement: function () {
            $("#agreement").remove();
            App.title("请绑定本人银行卡");
        },
        limitLen: function(event) {
            var lengths = 0;
            var id = event.target.id
            if(id == 'bankCode'){
                lengths = 19
                nonNumeric($('#'+id));
            }else if(id == 'username'){
                lengths = 20
                limitName($('#'+id),lengths);
                this.isEmpty();
                return;
            }
            limitLength($('#'+id),lengths);
            this.isEmpty();
        },
        luhmCheck: function (bankno){
            if(bankno.length==''){
                return {"success": false, "error": '银行卡不能为空'};
            }
            if (bankno.length < 14 || bankno.length > 19) {
    //$("#banknoInfo").html("银行卡号长度必须在16到19之间");
                return {"success": false, "error": '银行卡长度有误'};
            }
            var num = /^\d*$/; //全数字
            if (!num.exec(bankno)) {
    //$("#banknoInfo").html("银行卡号必须全为数字");
                return {"success": false, "error": '卡号必须为数字'};
            }
    //开头6位
    //         var strBin="10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99";
    //         if (strBin.indexOf(bankno.substring(0, 2))== -1) {
    // //$("#banknoInfo").html("银行卡号开头6位不符合规范");
    //             return false;
    //         }
            var lastNum=bankno.substr(bankno.length-1,1);//取出最后一位（与luhm进行比较）
            var first15Num=bankno.substr(0,bankno.length-1);//前15或18位
            var newArr=new Array();
            for(var i=first15Num.length-1;i>-1;i--){ //前15或18位倒序存进数组
                newArr.push(first15Num.substr(i,1));
            }
            var arrJiShu=new Array(); //奇数位*2的积 <9
            var arrJiShu2=new Array(); //奇数位*2的积 >9
            var arrOuShu=new Array(); //偶数位数组
            for(var j=0;j<newArr.length;j++){
                if((j+1)%2==1){//奇数位
                    if(parseInt(newArr[j])*2<9)
                        arrJiShu.push(parseInt(newArr[j])*2);
                    else
                        arrJiShu2.push(parseInt(newArr[j])*2);
                }
                else //偶数位
                    arrOuShu.push(newArr[j]);
            }
            var jishu_child1=new Array();//奇数位*2 >9 的分割之后的数组个位数
            var jishu_child2=new Array();//奇数位*2 >9 的分割之后的数组十位数
            for(var h=0;h<arrJiShu2.length;h++){
                jishu_child1.push(parseInt(arrJiShu2[h])%10);
                jishu_child2.push(parseInt(arrJiShu2[h])/10);
            }
            var sumJiShu=0; //奇数位*2 < 9 的数组之和
            var sumOuShu=0; //偶数位数组之和
            var sumJiShuChild1=0; //奇数位*2 >9 的分割之后的数组个位数之和
            var sumJiShuChild2=0; //奇数位*2 >9 的分割之后的数组十位数之和
            var sumTotal=0;
            for(var m=0;m<arrJiShu.length;m++){
                sumJiShu=sumJiShu+parseInt(arrJiShu[m]);
            }
            for(var n=0;n<arrOuShu.length;n++){
                sumOuShu=sumOuShu+parseInt(arrOuShu[n]);
            }
            for(var p=0;p<jishu_child1.length;p++){
                sumJiShuChild1=sumJiShuChild1+parseInt(jishu_child1[p]);
                sumJiShuChild2=sumJiShuChild2+parseInt(jishu_child2[p]);
            }
    //计算总和
            sumTotal=parseInt(sumJiShu)+parseInt(sumOuShu)+parseInt(sumJiShuChild1)+parseInt(sumJiShuChild2);
    //计算Luhm值
            var k= parseInt(sumTotal)%10==0?10:parseInt(sumTotal)%10;
            var luhm= 10-k;
            if(lastNum==luhm){
                return {"success": true, "error": ''};
            }
            else{
                return {"success": false, "error": '银行卡号不符合规范'};
            }

        },

        destroy: function () {
            this.undelegateEvents();
            this.$el.html("");
            delete this;
        },
    });
});